package com.ajhlp.app.phoneDetailQuery.controller;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import java.util.concurrent.ConcurrentHashMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ajhlp.app.phoneDetailQuery.model.ConfigurationNameEnum;
import com.ajhlp.app.phoneDetailQuery.model.PhoneNumDetail;
import com.ajhlp.app.phoneDetailQuery.service.IConfigModifyService;
import com.ajhlp.app.phoneDetailQuery.service.IPhoneNumDetailService;
import com.ajhlp.app.phoneDetailQuery.service.QueryPhoneDetailThread;

@Controller
public class QueryDetailController {
	
	private final static Map<String, QueryPhoneDetailThread> tasks = new ConcurrentHashMap<String, QueryPhoneDetailThread>();
	
	private final static List<String> successFiles = new Vector<String>();
	
	@ModelAttribute("tasks")
	public static Map<String, QueryPhoneDetailThread> getTasks() {
		return tasks;
	}
	
	@ModelAttribute("files")
	public static List<String> getSuccessfiles() {
		
		successFiles.clear();
		
		try {
			File folder = new File(IConfigModifyService.configProperties.get(ConfigurationNameEnum.SAVE_PATH.getName()));
			
			File[] childs = folder.listFiles();
			
			for(File child : childs){
				if(child.isFile() && child.getName().endsWith("txt")){
					successFiles.add(child.getName());
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
		}
		
		return successFiles;
	}


	private PhoneNumDetail phoneNumDetail = new PhoneNumDetail("", "", "");
	
	@ModelAttribute("detail")
	public PhoneNumDetail getPhoneNumDetail() {
		return phoneNumDetail;
	}

	@RequestMapping(value="/query/single",method=RequestMethod.GET)
	public String goToSingleQuery(){
		phoneNumDetail.setPhoneNum("");
		phoneNumDetail.setAreacode("");
		phoneNumDetail.setArea("");
		return "bg/querysingle";
	}
	@Resource
	private IPhoneNumDetailService phoneNumDetailService;
	
	public IPhoneNumDetailService getPhoneNumDetailService() {
		return phoneNumDetailService;
	}

	public void setPhoneNumDetailService(
			IPhoneNumDetailService phoneNumDetailService) {
		this.phoneNumDetailService = phoneNumDetailService;
	}

	@RequestMapping(value="/query/single",method=RequestMethod.POST)
	public String searchSingleQuery(String mobile){
		PhoneNumDetail result = phoneNumDetailService.getDetail(mobile);
		if(result == null){
			phoneNumDetail.setArea("未知");
			phoneNumDetail.setAreacode("未知");
			phoneNumDetail.setPhoneNum(mobile);
		}else{
			phoneNumDetail.setArea(result.getArea());
			phoneNumDetail.setAreacode(result.getAreacode());
			phoneNumDetail.setPhoneNum(result.getPhoneNum());
		}
		return "bg/querysingle";
	}
	
	@RequestMapping(value="/query/multi",method=RequestMethod.GET)
	public String goToMultiQuery(){
		return "bg/querymulti";
	}
	
	@RequestMapping(value="/query/multi",method=RequestMethod.POST)
	@ResponseBody
	public String searchMultiQuery(HttpServletRequest request){
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		if(!isMultipart){
			return "0";
		}
		
		FileItemFactory factory = new DiskFileItemFactory();

		// Create a new file upload handler
		ServletFileUpload upload = new ServletFileUpload(factory);
		BufferedReader br = null;
		// Parse the request
		try {
			@SuppressWarnings("unchecked")
			List<FileItem> items = upload.parseRequest(request);
			
			Iterator<FileItem> item = items.iterator();
			
			while (item.hasNext()) {
			    FileItem tmp = item.next();

			    if (tmp.isFormField()) {
			        
			    } else {
			       List<String> mobile = new ArrayList<String>();
			       
			       br = new BufferedReader(new InputStreamReader(tmp.getInputStream()));
			       
			       String phoneNum = "";
			       
			       while((phoneNum = br.readLine()) != null){
			    	   mobile.add(phoneNum);
			       }
			       
			       QueryPhoneDetailThread task = new QueryPhoneDetailThread(tmp.getName(),mobile, phoneNumDetailService);
			       
			       tasks.put(tmp.getName(), task);
			       
			       Thread t = new Thread(task);
			       t.start();
			    }
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			return "0";
		} finally {
			if(br != null){
				try {
					br.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
				}
			}
		}
		return "1";
	}
}
